<?php namespace App\Core\Repository\Criterias;

use App\Core\Repository\Criteria;
use App\Core\Repository\Repository;
use App\Core\Exceptions\RuntimeError;

class SortCriteria extends Criteria {
    
    protected $field;
    protected $type;

    public function __construct($field, $type = 'ASC') {
        if(!$field){
            throw new RuntimeError('SortCriteria error.field name error.');
        }
        if(!in_array(strtoupper($type), ['ASC', 'DESC'])){
            throw new RuntimeError('SortCriteria error.Type mast in [ASC, DESC].');
        }
        $this->field = $field;
        $this->type = strtoupper($type);
        $this->setName('sort_'.$this->field);
    }

    public function apply(Repository $repository){
        parent::apply($repository);
        $this->query->orderBy($this->formatField($this->model, $this->field), $this->type);
    }
}